package com.lovcreate.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by Administrator on 2016/7/21.
 */
public class UserLoginServletFilter implements Filter {

    private FilterConfig fc;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init");
        this.fc = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();

        System.out.println(request.getRequestURI());
        System.out.println(request.getRemoteUser());

        if (request.getRequestURI().endsWith("login.jsp") || request.getRequestURI().endsWith("UserLoginServlet")) {
            System.out.println("Filter1 start");
            filterChain.doFilter(servletRequest, servletResponse);
            System.out.println("filter1 end");
            return;
        }

        if (null == session.getAttribute("user")) {
            System.out.println("Filter1 start..");
            ((HttpServletResponse) servletResponse).sendRedirect("login.jsp");
            System.out.println("Filter1 end..");
            return;
        } else {
            System.out.println("Filter1 start...");
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        System.out.println("destroy");
    }
}
